
// Copyright (C) 2007 Richard Uhler
// This file is part of Esiply.
//
// Esiply is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License, Version 2,
// as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#include <assert.h>
#include <stdio.h>

#include "esni.h"

extern int yydebug;
extern int yy_flex_debug;
esni_interface_t* esni;

esni_value_t es_print(esni_context_t context)
{
    // Convert the first argument to a string, and print it followed by
    // a newline.
    esni_value_t str;
    esni->evaluate(context, "$1 = str;", &str, NULL);
    printf("%s\n", esni->get_string(context, str));
    esni_value_t und;
    esni->evaluate(context, "$1 = undefined;", &und, NULL);
    return und;
}

esni_value_t es_debug(esni_context_t context)
{
    // debug does nothing for shootout
    esni_value_t und;
    esni->evaluate(context, "$1 = undefined;", &und, NULL);
    return und;
}

int main(int argc, char* argv[])
{
    yydebug = 0;
    yy_flex_debug = 0;
    esni = esni_get_interface();

    // shootout is run like:
    // ./esiply-shootout script arg0
    // where arg0 is accessible in the program via arguments[0].
    // print prints its arguments followed by a newline
    assert(argc == 3);
    const char* filename = argv[1];
    const char* arg0 = argv[2];

    // Instantiate the interpreter
    esni_context_t context = esni->create(NULL);

    // Create the print function
    esni_value_t printfunc = esni->make_function(context, es_print, "str");
    esni->evaluate(context, "print = $1;", &printfunc, NULL);

    // Add debug function so libraries work
    esni_value_t debugfunc = esni->make_function(context, es_debug, "str");
    esni->evaluate(context, "debug = $1;", &debugfunc, NULL);

    // Create arguments[0]
    esni_value_t arg0val = esni->make_string(context, arg0);
    esni->evaluate(context, "arguments = {0: $1};", &arg0val, NULL);

    // Run the file.
    esni->run_file(context, filename);
    return 0;
}

